#' deg_cutmat UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd
#'
#' @importFrom shiny NS tagList
mod_deg_cutmat_ui <- function(id){
  ns <- NS(id)
  tagList(
    hr(),
    fluidRow(
      column(12,
             helpText("The False Discovery Rate (FDR) in the summary statistics table"),
             shinyWidgets::prettyRadioButtons(
               inputId = ns("fdrType"),
               label = "Choices False Discovery Rate : ",
               choices = c("adj.P.Val" = "adj.P.Val", "P.Value" = "P.Value"),
               selected = "P.Value",
               icon = icon("eye-dropper"),
               bigger = TRUE,
               inline = TRUE,
               fill = TRUE,
               plain = TRUE,
               status = "success",
               animation = "pulse"
             )
      ),
      column(12,hr()),
      column(6,sliderInput(ns("pvaluecut"), "P Value for stable", min = 0.01, max = 0.05,value = 0.01, step = 0.01)),
      column(6,sliderInput(ns("FCcut"), "FC for up&down genes", min = 1, max = 4,value = 2, step = 0.1))
    ),
    hr(),
    htmlOutput(ns("howmany")),
    hr(),
    downloadButton(ns("geneup"), "Download UP Gene list"),
    downloadButton(ns("genedown"), "Download DOWN Gene list"),
    hr(),
    DT::DTOutput(ns("cutmat"))
  )
}

#' deg_cutmat Server Functions
#'
#' @noRd
mod_deg_cutmat_server <- function(id,deg_data=""){
  moduleServer( id, function(input, output, session){
    ns <- session$ns

    cutmat <- reactive({
      df <- deg_data$deg()

      if (input$fdrType == "P.Value") {
        dd <- df %>%
          dplyr::filter(P.Value <= input$pvaluecut, abs(logFC) >= log2(input$FCcut))
      } else {
        dd <- df %>%
          dplyr::filter(adj.P.Val <= input$pvaluecut, abs(logFC) >= log2(input$FCcut))
      }

      dd$g <-
        ifelse( dd$logFC > 0,'UP','DOWN')

      dd

    })

    gene_down <- reactive({
      cutmat <- cutmat()
      cutmat %>%
        dplyr::filter(g == "DOWN") %>%
        row.names()
    })

    gene_up <- reactive({
      cutmat <- cutmat()
      cutmat %>%
        dplyr::filter(g == "UP") %>%
        row.names()
    })

    row_num <- reactive({
      cutmat <- cutmat()
      nrow(cutmat)
    })

    g_mun <- reactive({
      cutmat <- cutmat()
      # w = table(cutmat$g)
      # t = as.data.frame(w)
      # names(t)[1] = 'g'
      UP <- cutmat %>%
        dplyr::filter(g == "UP") %>%
        nrow()
      DOWN <- cutmat %>%
        dplyr::filter(g == "DOWN") %>%
        nrow()
      t <- c(UP,DOWN)
      names(t) <- c("UP","DOWN")
      t
    })
    # describe data dimension
    output$howmany <- renderText({
      g_mun <- g_mun()
      paste(
            "<font color=\"#0275D8\"><b>",row_num(), "</b></font>",
            "genes left",
            "<p>&#128008;</p>",
            "<font color=\"#0275D8\"><b>",g_mun["UP"], "</b></font>",
            "UP",
            "<p>&#128578;</p>",
            "<font color=\"#0275D8\"><b>",g_mun["DOWN"], "</b></font>",
            "DOWN",
            "<p>&#128579;</p>"
            )
    })

    output$geneup <- downloadHandler(
      filename = function() {
        paste("genelist-UP", Sys.Date(), ".txt", sep="")
      },
      content = function(file) {
        utils::write.table(gene_up(), file, sep = "",
                           row.names = FALSE,quote = FALSE,col.names = FALSE)
      }
    )

    output$genedown <- downloadHandler(
      filename = function() {
        paste("genelist-DOWN", Sys.Date(), ".txt", sep="")
      },
      content = function(file) {
        utils::write.table(gene_down(), file, sep = "",
                           row.names = FALSE,quote = FALSE,col.names = FALSE)
      }
    )

    output$cutmat <- DT::renderDT({
      DT::datatable( cutmat(), escape = FALSE,filter="top", selection="multiple",
                     rownames = TRUE,
                     style = "bootstrap4",
                     options=list(
                       sDom  = '<"top">flrt<"bottom">ip',
                       #columnDefs = list(list(className = 'dt-center', targets = 5)),
                       pageLength = 15,
                       lengthMenu = list(c(15, 50, 100, -1),c(15, 50, 100, "ALL")),
                       dom = 'Blfrtip',
                       scrollX = TRUE,
                       scrollY = TRUE,
                       fixedColumns = TRUE,
                       fixedHeader = TRUE
                     )
      )
    })

  })
}

## To be copied in the UI
# mod_deg_cutmat_ui("deg_cutmat_ui_1")

## To be copied in the server
# mod_deg_cutmat_server("deg_cutmat_ui_1")
